<?php

// +----------------------------------------------------------------------
// | 产品类别栏目
// +----------------------------------------------------------------------

namespace Admins\Controller;

use Common\Controller\AdminBase;

class CategoryController extends AdminBase {

    //栏目列表
    public function index() {
        if (IS_POST) {
            $Category = M('Category');
            foreach ($_POST['sort'] as $id => $sort) {
                $Category->where(array('cateid' => $id))->save(array('sort' => $sort));
            }
            $this->success("排序更新成功！");
            exit;
        }
        $categorys = array();
        //栏目数据，可以设置为缓存的方式
        $result = D('Admins/Category')->getData();
        if (!empty($result)) {
            foreach ($result as $r) {
                $r = getCategory($r['cateid']);
                if ($r['child']) {
                    $r['yesadd'] = '';
                } else {
                    $r['yesadd'] = 'blue';
                }

                $r['status']=showStatus($r['status']);
                if ($r['child']) {
                    $r['str_manage'] .= '<a href="' . U("Category/add", array("parentid" => $r['cateid'])) . '">添加子栏目</a> | ';
                }

                $r['str_manage'] .= '<a href="' . U("Category/edit", array("cateid" => $r['cateid'])) . '">修改</a> | <a class="J_ajax_del" data-msg="确定删除该栏目及栏目下的信息吗?" href="' . U("Category/delete", array("cateid" => $r['cateid'])) . '">删除</a>';
                //终极栏目转换
                $r['str_manage'] .= ' | <a href="' . U("Category/categoryTochild", array("cateid" => $r['cateid'])) . '">终极属性转换</a> ';

                $categorys[$r['cateid']] = $r;
            }
        }
        $str = "<tr><td align='center'><input name='sort[\$id]' type='text' size='3' value='\$sort' class='input'></td>
	<td align='center'>\$status</td>
	<td align='center'><font color='\$yesadd'>\$id</font></td>
	<td >\$spacer\$catename</td>
	<td align='center' >\$str_manage</td>
	</tr>";
        if (!empty($categorys) && is_array($categorys)) {
            $this->Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $this->Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $this->Tree->init($categorys);
            $categorydata = $this->Tree->get_tree(0, $str);
        } else {
            $categorydata = '';
        }
        $this->assign("categorys", $categorydata);
        $this->display();
    }

    //添加栏目
    public function add() {
        if (IS_POST) {
            $Category = D("Admins/Category");
            //批量添加
            $post = $_POST;
            if ($post['isbatch']) {
                //需要批量添加的栏目
                $batch_add = explode("\n", $post['batch_add']);
                if (empty($batch_add) || empty($post['batch_add'])) {
                    $this->error('请填写需要添加的栏目！');
                }
                unset($post['isbatch'], $post['batch_add'], $post['catename'], $post['enname']);
                //遍历数组
                foreach ($batch_add as $rs) {
                    $cat = explode('|', $rs, 2);
                    if ($cat[0] && $cat[1]) {
                        $post['catename'] = $cat[0];
                        $post['enname'] = $cat[1];
                        $Category->addCategory($post);
                    }
                }
            } else {
                unset($post['isbatch'],$post['batch_add']);
                $cateid = $Category->addCategory($post);
                if ($cateid) {
                    $this->success("添加成功！", U("Category/index"));
                } else {
                    $error = $Category->getError();
                    $this->error($error ? $error : '栏目添加失败！');
                }
            }
            $this->success("添加栏目成功！", U("Category/index"));
        }  else {
            $parentid = I('get.parentid', 0, 'intval');
            if (!empty($parentid)) {
                $Ca = getCategory($parentid);
                if (empty($Ca)) {
                    $this->error("父栏目不存在！");
                }
                if ($Ca['child'] == '0') {
                    $this->error("终极栏目不能添加子栏目！");
                }
            }
            //栏目列表 可以用缓存的方式
            $array = D("Admins/Category")->getData();
            foreach ($array as $k => $v) {
                $array[$k] = getCategory($v['cateid']);
                if ($v['child'] == '0') {
                    $array[$k]['disabled'] = "disabled";
                } else {
                    $array[$k]['disabled'] = "";
                }
            }
            if (!empty($array) && is_array($array)) {
                $this->Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
                $this->Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
                $str = "<option value='\$cateid' \$selected \$disabled>\$spacer \$catename</option>";
                $this->Tree->init($array);
                $categorydata = $this->Tree->get_tree(0, $str, $parentid);
            } else {
                $categorydata = '';
            }
            $this->assign("category", $categorydata);
            $this->display();
        }
    }

    //编辑栏目
    public function edit() {
        if (IS_POST) {
            $catid = I("post.cateid", "", "intval");
            if (empty($catid)) {
                $this->error('请选择需要修改的栏目！');
            }
            $Category = D("Admins/Category");
            $status = $Category->editCategory($_POST);
            if ($status) {
                $this->success("更新成功！", U("Category/index"));
            } else {
                $error = $Category->getError(); //获取MODEL中错误
                $this->error($error ? $error : '栏目修改失败！');
            }
        } else {
            $cateid = I('get.cateid', 0, 'intval');
            $array = D("Admins/Category")->getData();
            foreach ($array as $k => $v) {
                $array[$k] = getCategory($v['cateid']);
                if ($v['child'] == "0") {
                    $array[$k]['disabled'] = "disabled";
                } else {
                    $array[$k]['disabled'] = "";
                }
            }
            $data = getCategory($cateid);

            if (!empty($array) && is_array($array)) {
                $this->Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
                $this->Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
                $this->Tree->init($array);
                $str = "<option value='\$cateid' \$selected \$disabled>\$spacer \$catename</option>";
                $categorydata = $this->Tree->get_tree(0, $str, $data['parentid']);
            } else {
                $categorydata = '';
            }

            $this->assign("category", $categorydata);
            $this->assign("data", $data);

            $this->display();

        }
    }


    //更新栏目
    public function updates_catechild() {
        $db = M("Category");
        $data = $db->order(array('sort' => 'ASC'))->select();
        $categorys = array();
        foreach ($data as $v) {
            $categorys[$v['cateid']] = $v;
        }
        $this->repair($categorys); //更新栏目子目录及父目录
        $this->success('栏目更新成功');
    }



    //栏目属性转换  child 字段的转换
    public function categoryTochild() {
        $model=M('Category');
        $cateid = I('get.cateid', 0, 'intval');
        $r =$model->where(array("cateid" => $cateid))->find();
        if ($r) {
            $count = $model->where(array("parentid" => $cateid))->count();
            if ($count > 0) {
                $this->error("该栏目下已经存在栏目，无法转换！");
            } else {
                $count = M(ucwords('item'))->where(array("cateid" => $cateid))->count();
                if ($count) {
                    $this->error("该栏目下已经存在数据，无法转换！");
                }
                $child = $r['child'] ? 0 : 1;
                $status = $model->where(array("cateid" => $cateid))->save(array("child" => $child));
                if ($status !== false) {
                    $this->success("栏目属性转换成功！");
                } else {
                    $this->error("栏目属性转换失败！");
                }
            }
        } else {
            $this->error("栏目不存在！");
        }
    }

    /**
     * 修复栏目数据,重置arrparentid,arrchildid
     * @param type $categorys 需要修复的栏目数组
     * @return boolean
     */
    protected function repair($categorys) {
        if (is_array($categorys)) {
            foreach ($categorys as $cateid => $cat) {

                //获取父栏目ID列表
                $arrparentid = D("Admins/Category")->getArrparentid($cateid);
                //获取子栏目ID列表
                $arrchildid = D("Admins/Category")->getArrchildid($cateid);
                //检查所有父id 子栏目id 等相关数据是否正确，不正确更新
                if ($categorys[$cateid]['arrparentid'] != $arrparentid || $categorys[$cateid]['arrchildid'] != $arrchildid) {
                    D("Admins/Category")->where(array('cateid' => $cateid))->save(array('arrparentid' => $arrparentid, 'arrchildid' => $arrchildid));
                }
                //刷新单栏目缓存
                getCategory($cateid, '', true);
            }
        }
        return true;
    }




//删除栏目
    public function delete() {
        $cateid = I("get.cateid", "", "intval");
        if (!$cateid) {
            $this->error("请指定需要删除的栏目！");
        }
        $Category=D("Admins/Category");
        if (false == $Category->deleteCateid($cateid)) {
            $error = $Category->getError(); //获取MODEL中错误
            $this->error($error ? $error : '栏目删除失败！');
        }
        $this->success("栏目删除成功！", U("Category/index"));
    }
}
